package com.wr.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wr.common.entity.TbSysUser;
import com.wr.common.mapper.TbSysUserMapper;
import com.wr.service.LoginService;
import com.wr.service.consumer.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

@Service
public class LoginServiceIml implements LoginService {
    // 日志
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginServiceIml.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private TbSysUserMapper tbSysUserMapper;

    @Override
    public TbSysUser login(String loginCode, String plantPassword) {
        TbSysUser tbSysUser = null;
        // 先去redis里取
        String json = redisService.get(loginCode);
        // 登录  用户信息不在缓存中
        if (StrUtil.isBlank(json)){
            Example example = new Example(TbSysUser.class);
            example.createCriteria().andEqualTo("loginCode",loginCode);
            tbSysUser = tbSysUserMapper.selectOneByExample(example);
            String password = DigestUtils.md5DigestAsHex(plantPassword.getBytes());
            if (tbSysUser!=null && tbSysUser.getPassword().equals(password)){
                // 添加到redis
                redisService.put(loginCode,JSON.toJSONString(tbSysUser), 60*60*24); // 存一天
                return tbSysUser;
            }else {
                return null;
            }
        }
        // 缓存有数据
        else {
            tbSysUser = JSONArray.parseObject(json, TbSysUser.class);
        }
        return tbSysUser;
    }
}
